import 'package:fluent_ui/fluent_ui.dart';
import 'package:flutter/material.dart' show DataCell, DataColumn;
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:go_router/go_router.dart';
import 'package:provider/provider.dart';

import '../../components/buttons.dart';
import '../../components/data_table.dart';
import '../../model/semester_model.dart';
import '../../route/router.dart';
import '../../utils/date_utils.dart';
import '../app/app_dict_data.dart';
import 'semester_view_model.dart';

class SemesterViewList extends StatefulWidget {
  const SemesterViewList({super.key});

  @override
  State<SemesterViewList> createState() => _SemesterViewListState();
}

class _SemesterViewListState extends State<SemesterViewList> {
  final queryFormKey = GlobalKey<FormState>();
  final tableKey = GlobalKey<DataTableState<SemesterItemRes>>();
  DateTime? now;

  @override
  void initState() {
    super.initState();
    //加载数据
    final model = context.read<SemesterViewModel>();
    model.loadInit(afterHandler: () => query(model));
  }

  void query(final SemesterViewModel model) => model.query();

  Widget buildQueryForm(final SemesterViewModel model) {
    Widget buildField(SemesterQueryField field,
        Widget Function(TextEditingController? c, String label) handler) {
      final label = field.label;
      final controller = model.getController(field);
      final child = handler.call(controller, label);
      return SizedBox(
        width: 128.w,
        child: InfoLabel(
          label: label,
          child: child,
        ),
      );
    }

    return Form(
      key: queryFormKey,
      child: Wrap(
        spacing: 5.w,
        children: [
          //标题
          buildField(
            SemesterQueryField.title,
            (ctr, label) => TextFormBox(controller: ctr, placeholder: label),
          ),
          //当前日期
          buildField(
            SemesterQueryField.now,
            (ctr, label) => DatePicker(
              selected: now,
              onChanged: (dt) {
                ctr?.text = dateUtils.format('yyyy-MM-dd', dt);
                setState(() => now = dt);
              },
            ),
          ),
          //状态
          buildField(
            SemesterQueryField.status,
            (ctr, label) => ComboboxFormField(
              placeholder: Text(label),
              items: model.statusOpts,
              onChanged: (val) => ctr?.text = val ?? '',
            ),
          ),
        ],
      ),
    );
  }

  Widget buildQueryBars(final SemesterViewModel model) => Wrap(
        spacing: 2.w,
        children: [
          //查询
          buttons.query(onPressed: () => query(model)),
          //重置
          buttons.reset(onPressed: () {
            queryFormKey.currentState?.reset();
            model.cleanQueryFields();
            query(model);
          }),
          //新增
          buttons.add(onPressed: () => editHandler(model, null)),
        ],
      );

  void editHandler(final SemesterViewModel model, final String? id) async {
    final ret = await context.pushNamed<bool>(
      getRoteName(AppRote.semesterEdit),
      queryParameters: {'id': id ?? ''},
    );
    if (ret ?? false) {
      //查询数据
      query(model);
    }
  }

  @override
  Widget build(final BuildContext context) => Consumer<SemesterViewModel>(
        builder: (context, model, _) => ScaffoldPage.scrollable(
          header: Column(
            children: [
              PageHeader(title: const Text('学年学期')),
              Padding(
                padding: () {
                  final padding = PageHeader.horizontalPadding(context);
                  return EdgeInsetsDirectional.symmetric(horizontal: padding);
                }(),
                child: Row(
                  children: [
                    //查询条件
                    buildQueryForm(model),
                    //占位
                    Expanded(child: Container()),
                    //查询按钮
                    buildQueryBars(model),
                  ],
                ),
              ),
              SizedBox(height: 15.h),
            ],
          ),
          children: [
            //数据列表
            buildTable(model),
          ],
        ),
      );

  Widget buildTable(final SemesterViewModel model) {
    final labels = <String>['编码', '名称', '开始日期', '结束日期', '状态', '创建时间', '操作'];
    DataCell buildCell(String? Function() handler) => DataCell(Text(
          handler.call() ?? '',
          softWrap: false,
          overflow: TextOverflow.ellipsis,
        ));

    final String dFormat = 'yyyy-MM-dd', dtFormat = '$dFormat HH:mm:ss';
    return DataTable<SemesterItemRes>(
      key: tableKey,
      model: model.queryModel,
      columns: labels.map((label) => DataColumn(label: Text(label))).toList(),
      onLoadData: () => query(model),
      onRowCallback: (row) => [
        //编码
        buildCell(() => row.code),
        //名称
        buildCell(() => '${row.title}${row.isDefault == 1 ? '【默认】' : ''}'),
        //开始日期
        buildCell(() => dateUtils.format(dFormat, row.start)),
        //结束日期
        buildCell(() => dateUtils.format(dFormat, row.end)),
        //状态
        buildCell(() => appDictData.getLabel('status', row.status)),
        //创建时间
        buildCell(() => dateUtils.format(dtFormat, row.createdAt)),
        //操作
        DataCell(OverflowBar(
          spacing: 2.w,
          children: [
            //修改
            buttons.modify(onPressed: () {
              final id = row.id;
              if (id.isNotEmpty) {
                editHandler(model, id);
              }
            }),
            //删除
            buttons.delete(onPressed: () {
              final id = row.id;
              if (id.isNotEmpty) {
                model.onDeleteHandler(id);
              }
            }),
          ],
        ))
      ],
    );
  }
}
